package com.bckj.fastboot.iot.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bckj.fastboot.core.extra.cache.CacheOps;
import com.bckj.fastboot.core.lang.model.PageResult;
import com.bckj.fastboot.core.page.PageSupport;
import com.bckj.fastboot.iot.biz.repository.IotAlarmRuleRepository;
import com.bckj.fastboot.iot.common.constant.IotCacheConstants;
import com.bckj.fastboot.iot.common.dto.query.IotAlarmRuleQuery;
import com.bckj.fastboot.iot.common.dto.response.IotAlarmRuleResponse;
import com.bckj.fastboot.iot.common.entity.IotAlarmRule;
import com.bckj.fastboot.iot.biz.service.IotAlarmRuleQueryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * IotAlarmRuleQueryServiceImpl
 *
 * @author wfc
 **/
@Service
@RequiredArgsConstructor
public class IotAlarmRuleQueryServiceImpl implements IotAlarmRuleQueryService {
    private final IotAlarmRuleRepository iotAlarmRuleRepository;
    private final CacheOps cacheOps;

    @Override
    public IotAlarmRuleResponse details(Long id) {
        return iotAlarmRuleRepository.getBaseMapper().findById(id);
    }

    @Override
    public List<IotAlarmRuleResponse> findList(IotAlarmRuleQuery query) {
        return iotAlarmRuleRepository.getBaseMapper().findList(query);
    }

    @Override
    public PageResult<IotAlarmRuleResponse> page(IPage<IotAlarmRuleResponse> page, IotAlarmRuleQuery query) {
        var result = PageSupport.page(page, query, this::findList);
        return PageResult.of(result);
    }

    @Override
    public List<IotAlarmRule> findRules(String protocolCode, String cmd) {
        String key = protocolCode + cmd;
        var cache = cacheOps.redisCache(IotCacheConstants.IOT_ALARM_RULE_KEY_PREFIX);
        return cacheOps.runCaching(cache,
                () -> iotAlarmRuleRepository.lambdaQuery()
                        .eq(IotAlarmRule::getProtocolCode, protocolCode)
                        .eq(IotAlarmRule::getCmd, cmd)
                        .list(), key
        );
    }

}
